package org.miage.annuaire.bean;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;

import javax.servlet.ServletContext;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.struts2.ServletActionContext;
import org.miage.annuaire.data.DataAccessFactory;
import org.miage.annuaire.data.XmlDataAccess;
import org.miage.annuaire.pdf.xml2pdf;
import org.w3c.dom.Document;

import com.opensymphony.xwork2.ActionSupport;

public class PdfBean extends ActionSupport {
	
	@Override
	public String execute() throws Exception {
		
        // Recupere le fichier de style ------------------------------------
        InputStream xsl = this.getServletContext().getResourceAsStream(
        		"WEB-INF/configurationXML/pdf.xsl");
        
        String[] splittedQuery = this.query.split(",");
        Document document = null;
        
        if (this.query.trim().isEmpty()) {
        	this.addErrorMessage("Veuillez sélectionner au moins une "
        			+ "structure.");
        	return ERROR;
        }
        
        try {
        	if (this.allChecked == true) {
            	document = this.getXmlDataAccess().getAllStructures();
            } else {
            	document = this.getXmlDataAccess().getStructuresByKeys(
            			Arrays.asList(splittedQuery));
            }
        } catch (ParserConfigurationException e) {
        	this.addActionError(e.getMessage());
        	return ERROR;
        }
        

        // Transforme le resultat en fichier PDF ---------------------------
        xml2pdf pdf2 = new xml2pdf();
        FileInputStream f = pdf2.extract2stream(document, xsl,
        		this.getServletContext().getRealPath("/") + "/");
        
        this.inputStream = f;
		
		return SUCCESS;
	}
	
	/**
	 * @return the pdfInputStream
	 */
	public InputStream getInputStream() {
		return this.inputStream;
	}

	public String getQuery() {
		return this.query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public boolean isAllChecked() {
		return this.allChecked;
	}

	public void setAllChecked(boolean allChecked) {
		this.allChecked = allChecked;
	}

	protected XmlDataAccess getXmlDataAccess() {
		return DataAccessFactory.getInstance().getXmlDataAccess();
	}
	
	protected ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	
	protected void addErrorMessage(String message) {
		this.addActionError(message);
	}
	
	private InputStream inputStream = null;
	
	private String query = null;
	
	private boolean allChecked = true;
}
